package servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Pet;
import service.PetService;

@WebServlet("/add")
public class AddServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");

		Pet pet = new Pet();
		pet.setPetName(req.getParameter("petName"));
		pet.setDesc(req.getParameter("desc"));
		pet.setPetBreed(req.getParameter("petBreed"));
		pet.setPetSex(req.getParameter("petSex"));
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date birthday = simpleDateFormat.parse(req.getParameter("birthday"));
			pet.setBirthday(birthday);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		PetService petService = new PetService();
		int n = petService.addPet(pet);
		if(n > 0){
			resp.getWriter().print("<script>alert('添加成功');location.href='select';</script>");
		}else{
			resp.getWriter().print("<script>alert('添加失败');location.href='add.jsp';</script>");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
